package it.basketstats.activities;

import it.basketstats.R;
import it.basketstats.activities.AddTeamDialog.addTeamListener;
import it.basketstats.utility.DB.StatsDB;
import it.basketstats.utility.DB.TeamEntity;

import java.util.ArrayList;

import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class TeamActivity extends Activity implements addTeamListener {

	private StatsDB db;
	private String selectedTeam;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_team);

		db = new StatsDB(this);
		db.open();

		updateTeamList();
		
		ListView teamList = (ListView) findViewById(R.id.team_list);
		teamList.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				TextView tv = (TextView) parent.getChildAt(position);
				selectedTeam = tv.getText().toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.team, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_addTeam:
			DialogFragment d = new AddTeamDialog();
			d.show(this.getFragmentManager(), "add_team");
			return true;
		case R.id.action_deleteTeam:
			deleteTeam();
			return true;
		case R.id.action_settings:
			// TODO (forse)
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void updateTeamList() {
		ListView teamList = (ListView) findViewById(R.id.team_list);

		ArrayList<TeamEntity> teams = db.teamGetAll();
		if (teams != null) {
			ArrayList<String> names = new ArrayList<String>();
			for (TeamEntity team : teams) {
				names.add(team.getName());
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, names);
			teamList.setAdapter(adapter);
		}
	}

	@Override
	// callback function from AddTeamDialog
	public void addTeam(String name) {
		db.teamAdd(name);
		updateTeamList();
	}
	
	private void deleteTeam () {
		db.teamDelete(db.teamGetID(selectedTeam));
	}

}
